<template>
  <!-- 卡位  我租的卡位 我使用的-->
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form-new" label-width="80px">
      <el-form-item label="运营商" prop="carrierType">
        <el-select v-model="queryParams.carrierType" placeholder="请选择运营商" clearable>
          <el-option v-for="dict in carrierTypes" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="手机号" prop="tel">
        <el-input v-model="queryParams.tel" placeholder="请输入手机号" clearable size="small" />
      </el-form-item>
      <el-form-item label="在线状态" prop="deviceStatus">
        <el-select v-model="queryParams.deviceStatus" placeholder="请选择在线状态" clearable>
          <el-option label="在线" :value="1" />
          <el-option label="离线" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择状态" clearable>
          <el-option label="正常" :value="1" />
          <el-option label="即将到期" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item class="btns">
        <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button type="warning" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        <el-button type="success" icon="el-icon-plus" @click="openShare">分享</el-button>
      </el-form-item>

    </el-form>
    <div style="color: #999;margin-bottom: 10px;">
      到期前请及时续费，到期后将无法续费，损失自行承担。
    </div>
    <div class="table_box" v-loading="loading">
      <el-table ref="table" :data="tableData.records" style="width: 100%" stripe>
        <!-- <el-table-column type="selection" width="55">
        </el-table-column> -->
        <el-table-column prop="chuzufangName" label="管理方" width="150"></el-table-column>
        <el-table-column prop="carrierType" label="运营商">
          <template slot-scope="scope">
            <template v-if="carrierTypes&&carrierTypes[1]">
              <span :key="scope.row.id" :style="{color:colors[scope.row.carrierType]}">
                {{carrierTypes[scope.row.carrierType].name}}
              </span>
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="tel" label="手机号" width="130"></el-table-column>
        <el-table-column prop="remark" label="在线状态" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.deviceStatus==1" type="success">在线</el-tag>
            <el-tag v-else type="danger">离线</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="绑定商品数" width="100">
          <template slot-scope="scope">
            <span class="bangding" @click="tanchuangceng(scope.row.content, carrierTypes[scope.row.carrierType].name)">{{scope.row.count||0}}</span>
            <div class="tag">
              {{ getEndTime(scope.row) }}
            </div>
            <div style="color: #666;">
              {{ `180天绑定${scope.row.daysCot||0}次` }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="剩余时间" width="100">
          <template slot-scope="scope">
            <span :style="{color:getShengyuDays(scope.row)<=queryParams.day?'red':'green'}">{{getShengyuDays(scope.row)}}天</span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag type="danger" v-if="getShengyuDays(scope.row)<=queryParams.day">即将到期</el-tag>
            <el-tag type="success" v-if="getShengyuDays(scope.row)>queryParams.day">正常</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="zulinTime" label="开始时间" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.zulinTime">
              {{ scope.row.zulinTime.substring(0, 10)}}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="expireTime" label="到期时间" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.expireTime">
              {{ scope.row.expireTime.substring(0, 10)}}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="no" label="共享单号" width="200">

          <template slot-scope="scope">
            <span class="link" @click="openOrderDialog(scope.row.no)">
              {{ scope.row.no }}
            </span>
          </template>
        </el-table-column>

        <!-- <el-table-column prop="custodian" label="保管人" width="100"></el-table-column> -->

        <!-- <el-table-column prop="gameStr" label="游戏运营商" min-width="250">
          <template slot-scope="scope">
            <div class="bangding-box" v-if="scope.row.carrierTypeVoList">
              <div class="bditem flex" v-for="item in scope.row.carrierTypeVoList" :key="item.id">
                <span style="width:100px;text-align:right;overflow:hidden;white-space: nowrap;">{{item.name}}</span>
                <span class="bangding" @click="tanchuangceng(item.content, item.name)">绑定商品:{{item.count}}</span>
                <span>到期时间:{{item.expireTime}}</span>
                <span>状态:
                </span>
                <span v-if="item.chuzufangEnable==1" style="color:green">启用</span>
                <span v-if="item.chuzufangEnable==2" style="color:red">停用</span>

              </div>
            </div>
            <div v-else>暂无</div>
          </template>
        </el-table-column> -->

        <el-table-column fixed="right" label="操作" width="260">
          <template slot-scope="scope">
            <el-button type="edit" @click="xufei(scope.row)">续费</el-button>
            <!-- <el-button type="edit" @click="editRow(scope.row)">编辑</el-button> -->
            <el-button type="text" @click="viewRecords(scope.row)">绑定记录</el-button>

            <el-button type="text" @click="sendSms(scope.row)" v-if="checkPermi(['phoneManage:fasongduanxin'])">发送短信</el-button>
            <!-- <el-button type="edit" @click="fenxiang(scope.row)">短信分享</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="tableData.total > 0" :total="tableData.total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </div>

    <!-- <addDialog ref="addDialog"></addDialog> -->
    <!-- 系列弹窗 -->
    <el-dialog class="diologs" append-to-body :title="names" :visible.sync="dialogVisiblese" width="800px">
      <div style="min-height: 300px;">
        <el-tabs v-model="activeName">
          <el-tab-pane v-for="(item, index) in xilie" :key="index" :label="item.name+'('+item.list.length+')'" :name="''+index">
            <div class="twos" style="color: #1abc9c">
              {{ '绑定的账号' }}
            </div>
            <div class="twos" v-for="(item1, index1) in item.list" :key="index1">
              {{ item1 }}
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
    <!-- 绑定记录弹窗 -->
    <viewRecordsDialog ref="viewRecordsDialog"></viewRecordsDialog>
    <!-- 发送短信弹窗 -->
    <sendSmsDialog ref="sendSmsDialog"></sendSmsDialog>
    <!-- 创就按分享链接 -->
    <addFenxiangDialog ref="addFenxiangDialog"></addFenxiangDialog>
    <!-- 创就按分享链接 -->
    <addFenxiangPiliang ref="addFenxiangPiliang"></addFenxiangPiliang>
    <!-- 共享订单弹窗 -->
    <shareOrderDialog ref="shareOrderDialog"></shareOrderDialog>
    <!-- 号码续费弹窗 -->
     <telXufei ref="telXufei" @saved="getList"></telXufei>
  </div>
</template>

<script>
import viewRecordsDialog from "../components/viewRecords";
import sendSmsDialog from "../components/sendSmsDialog";
import phoneApi from "@/api/phoneManage";
import addFenxiangDialog from "../components/addFenxiang";
import addFenxiangPiliang from "../components/addFenxiangPiliang.vue";
import shareOrderDialog from "../gongxiang/shareOrderDialog.vue";
import telXufei from "../gongxiang/telXufei.vue";
import { getTenantPushSettingsByTenantId } from "@/api/system/shopManage";
export default {
  name: "Wozude",
  components: {
    viewRecordsDialog,
    sendSmsDialog,
    addFenxiangDialog,
    addFenxiangPiliang,
    shareOrderDialog,
    telXufei
  },
  data() {
    return {
      colors: [
        "red",
        "green",
        "FFB52B",
        "#6c5dd2",
        "red",
        "green",
        "FFB52B",
        "#6c5dd2",
      ],
      activeName: "0",
      names: "",
      xilie: [],
      dialogVisiblese: false,
      tableData: {
        records: [],
        total: 0,
      },
      loading: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        isLease: 1,
        carrierType: "",
        tel: "",
        deviceStatus: "",
        state:'',
        day:10,//即将到期天数
      },
      multipleSelection: [],
      lengQueObj: {},
    };
  },
  computed: {
    shopInfo() {
      return this.$store.getters.shopInfo;
    },
    carrierTypes() {
      return this.arrayToObject(this.$store.getters.gameYunyingshangList, "id");
    },
    getShengyuDays() {
      return (row) => {
        let result = 0;
        if (row.expireTime) {
          // 获取当前日期和时间
          const today = new Date();

          // 将输入的日期转换为Date对象
          const future = new Date(row.expireTime);

          // 计算两个日期之间的毫秒差
          const diffTime = future.getTime() - today.getTime();

          // 将毫秒转换为天数
          const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

          // 如果日期是过去的，返回0
          result = diffDays > 0 ? diffDays : 0;
        }
        return result;
      };
    },
    // 计算冷却期剩余
    getEndTime() {
      return (val) => {
        if (!this.lengQueObj[val.carrierType]) {
          return "";
        }
        if (!val.maxCreateTime) {
          return "";
        }
        let result = "";
        const lengque = this.lengQueObj[val.carrierType]
        const now = new Date();
        const start = new Date(val.maxCreateTime);
        if (start) {
          const days = Number(lengque);
          if (days > 0) {
            // 计算时间差（毫秒）
            const timeDiff = now.getTime() - start.getTime();
            if (timeDiff > 0) {
              // 将毫秒转换为天数（1天 = 24 * 60 * 60 * 1000毫秒）
              const daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
              const shengyu = days - daysDiff;
              if (shengyu > 0) {
                result = `冷却剩余${shengyu}天`;
              }
              // if (shengyu > 0 && shengyu <=1) {
              //   result = `即将结束冷却`;
              // }
            }
          }
        }
        return result;
      };
    },
  },
  created() {
    this.getList();
    this.getLengQue()
  },
  activated() {},
  methods: {
    //系列弹层
    tanchuangceng(row, i) {
      //console.log(111);
      if (row.length == 0) {
        this.dialogVisiblese = false;
        this.$message({
          message: "暂未绑定！",
          type: "warning",
        });
        return;
      }
      this.dialogVisiblese = true;
      //console.log(row);
      this.xilie = row;
      this.names = i;
      // this.listOne = row[0].list;
      // this.nameyouxi = row[0].name;
    },
    // 获取手机号冷却时间
    getLengQue() {
      if(this.shopInfo){
        getTenantPushSettingsByTenantId({
          tenantId:this.shopInfo.tenantId,
          type: 6, //6 手机号冷却设置
        }).then((res) => {
          if (res.data && res.data.settingsJson) {
            this.lengQueObj = JSON.parse(res.data.settingsJson);
          }
        });
      }
    },
    // 打开共享订单
    openOrderDialog(no) {
      this.$refs.shareOrderDialog.open({
        dataType: 2,
        no: no,
      });
    },
    // 获取列表
    getList() {
      this.loading = true;
      // this.tableData.records = []
      phoneApi.telLeaseDetailslist(this.queryParams).then((response) => {
        this.tableData.records = response.rows;
        this.tableData.total = response.total;
        this.loading = false;
        this.$nextTick(() => {
          this.$refs.table.doLayout();
        });
        // if (response.rows && response.rows.length) {
        //   this.rise = response.rows[0].rise;
        // }
      });
    },
    handleSelectionChange(val) {
      console.log("%c Line:162 🍯 val", "color:#ffdd4d", val);
      this.multipleSelection = val;
    },
    // 搜索
    search() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 创建分享
    fenxiang(row) {
      this.$refs.addFenxiangDialog.open(row, "wozude");
    },
    // 创建批量分享
    openShare() {
      this.$refs.addFenxiangPiliang.open([], "wozude");
      // if(this.multipleSelection&&this.multipleSelection.length){
      //   this.$refs.addFenxiangPiliang.open(this.multipleSelection, "wozude");
      // }else{
      //   return this.$message.error('请先选择手机号！')
      // }
    },
    // 状态改变
    statusChange(e, item) {
      phoneApi
        .telLeaseDetailsEdit({
          id: item.telLeaseDetailsId,
          zulinEnable: e,
        })
        .then((res) => {
          this.$message.success(res.msg);
          //console.log("%c Line:194 🌰 res", "color:#3f7cff", res);
          this.getList();
        });
    },
    // 打开新增弹窗
    openAdd() {
      this.$refs.addDialog.open();
    },
    // 打开编辑弹窗
    editRow(row) {
      this.$refs.addDialog.open("edit", row);
    },
    // 续费
    xufei(row){
      this.$refs.telXufei.open(row);
    },
    // 查看换绑记录
    viewRecords(row) {
      this.$refs.viewRecordsDialog.open(row.tel);
    },
    // 发送短信
    sendSms(row) {
      this.$refs.sendSmsDialog.open(
        {
          telManageId: row.telManageId,
          carrierTypeVoList: [
            {
              ...this.carrierTypes[row.carrierType],
            },
          ],
        },
        "zude"
      );
    },

    //重置
    resetQuery() {
      this.resetForm("queryForm");
      this.getList();
    },
  },
};
</script>
<style lang="scss" scoped>
.ones {
  width: 166px;
  height: 42px;
  text-align: center;
  line-height: 42px;
  border: 1px solid #ccc;
}

.two {
  text-align: center;
  width: 300px;
}

.twos {
  width: 100%;
  padding: 11px 20px;
  border: 1px solid #f2f2f2;
}
.bangding {
  cursor: pointer;
  color: $primary;
  padding: 0 10px;
}
// .bangding-box {
//   display: flex;
//   // justify-content: center;
//   flex-wrap: wrap;
//   .bditem {
//     margin-right: 20px;

//     // color: $primary;
//     > span {
//       margin-right: 10px;
//     }
//     .bangding {
//       cursor: pointer;
//       color: $primary;
//     }
//     &:nth-child(2n) {
//       margin-right: 0;
//     }
//   }
// }
.tag {
    background-color: #f49600;
    font-size: 12px;
    line-height: 22px;
    border-radius: 11px;
    color: #fff;
  }
</style>